<template>
	<div class="watermark-container" ref="parentref">
		<slot></slot>
	</div>
</template>
<script>
import waterMarkBg from './waterMarkBg'
export default {
	name: 'WaterMark',
	props: {
		text: {
			type: String,
			default: () => {
				return 'watermask'
			}
		},
		fontSize: {
			type: Number,
			default: () => {
				return 40
			}
		},
		gap: {
			type: Number,
			default: () => {
				return 100
			}
		},
		flag: {
			type: Number,
			default: () => {
				return 1
			}
		}
	},
	data() {
		return {
			ob: null,
			div: null
		}
	},
	watch: {
		text: function (oldval, newval) {
			this.init()
		},
		flag: function (oldval, newval) {
			this.init()
		}
	},
	methods: {
		init() {
			if (!this.$refs.parentref) {
				return
			}
			const { base64, styleSize } = waterMarkBg({ text: this.text, fontSize: this.fontSize, gap: this.gap })
			this.div = document.createElement('div')
			this.div.style.backgroundImage = `url(${base64})`
			this.div.style.backgroundSize = `${styleSize}px ${styleSize}px`
			this.div.style.backgroundRepeat = 'repeat'
			this.div.style.width = '100%'
			this.div.style.height = '100%'
			this.div.style.zIndex = 999
			this.div.style.position = 'absolute'
			this.div.style.inset = 0
			this.div.style.pointerEvents = 'none'
			this.$refs.parentref.appendChild(this.div)
		}
	},
	mounted() {
		this.ob = new MutationObserver((recordes) => {
			for (const record of recordes) {
				for (const dom of record.removedNodes) {
					if (dom === this.div) {
						this.init()
						return
					}
				}
			}
		})
		this.ob.observe(this.$refs.parentref, {
			childList: true,
			attributes: true,
			subtree: true
		})
	},
	destroyed() {
		this.ob && this.ob.disconnect()
		this.div = null
	}
}
</script>
<style>
.watermark-container {
	position: relative;
}
</style>
